import {
  Component,
  EventEmitter,
  Input,
  OnChanges,
  OnInit,
  Output,
  SimpleChanges,
} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-edit-account',
  templateUrl: './edit-account.component.html',
  styleUrls: ['./edit-account.component.less'],
})
export class EditAccountComponent implements OnInit, OnChanges {
  @Input() isVisible = false;
  @Output() editCancel = new EventEmitter<boolean>();
  @Input() data: any;
  listOfRole: any[] = [];
  validateForm!: FormGroup;
  nzOkLoading = false;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      _id: null,
      username: [null, [Validators.required]],
      realname: [null, [Validators.required]],
      roles: [],
      email: [null, [Validators.email]],
      mobile: [null, [Validators.pattern(/^0?(13|14|15|17|18|19)[0-9]{9}$/)]],
    });
  }

  ngOnChanges(simpleChange: SimpleChanges): void {
    if (simpleChange.data?.currentValue) {
      this.validateForm.patchValue(simpleChange.data?.currentValue);
    } else {
      this.validateForm?.reset();
    }
    this.nzOkLoading = false;
  }

  onEditOk(): void {
    this.editCancel.emit();
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(i)) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    }
    if (!this.validateForm.valid) {
      return;
    }
    this.nzOkLoading = true;
    // const { ...param } = this.validateForm.value;
    // dosomething here
  }
}
